package pro1.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pro1.dao.CharacterMapper;
import pro1.dao.CharacterModuleMapper;
import pro1.model.CharacterModule;
import pro1.model.ResponseBody;
import pro1.service.CharacterService;

@Service
public class CharacterServiceImpl implements CharacterService {

	@Autowired
	CharacterMapper characterMapper;

	@Autowired
	CharacterModuleMapper characterModuleMapper;

	@Override
	public ResponseBody all() {
		return new ResponseBody(1, "成功", characterMapper.selectAll());
	}

	@Override
	public ResponseBody addOrUpdateDep(Integer chaId, String name, String info) {
		ResponseBody response = new ResponseBody(1, "成功");
		if (chaId == null) {
			pro1.model.Character cha = characterMapper.selectByName(name);
			if (cha == null) {
				cha = new pro1.model.Character();
				cha.setName(name);
				cha.setInfo(info);
				characterMapper.insertSelective(cha);
			} else {
				response = new ResponseBody(0, "该角色已存在");
			}
		} else {
			pro1.model.Character cha = characterMapper.selectByPrimaryKey(chaId);
			if (cha == null) {
				response = new ResponseBody(0, "该角色不存在");
			} else {
				cha.setName(name);
				cha.setInfo(info);
				characterMapper.updateByPrimaryKeySelective(cha);
			}
		}
		return response;
	}

	@Override
	public ResponseBody deleteDep(Integer chaId) {
		ResponseBody response = new ResponseBody(1, "成功");
		pro1.model.Character cha = characterMapper.selectByPrimaryKey(chaId);
		if (cha == null) {
			response = new ResponseBody(0, "该部门不存在");
		} else {
			characterMapper.deleteByPrimaryKey(chaId);
		}
		return response;
	}

	@Override
	public ResponseBody setModules(Integer chaId, List<Integer> modules) {
		ResponseBody response = new ResponseBody(1, "成功");
		if (modules != null) {
			characterModuleMapper.deleteByCharacterId(chaId);
			for (Integer moduleId : modules) {
				CharacterModule characterModule = new CharacterModule();
				characterModule.setCharacterid(chaId);
				characterModule.setModuleid(moduleId);
				characterModuleMapper.insertSelective(characterModule);
			}
		}
		return response;
	}
}
